package com.jt.assistant.ui

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import androidx.recyclerview.widget.GridLayoutManager
import com.blankj.utilcode.util.GsonUtils
import com.cl.picture_selector.ImagePicker
import com.google.gson.reflect.TypeToken
import com.jt.assistant.R
import com.jt.assistant.adapter.PicAdapter
import com.jt.assistant.base.GlobalConfig
import com.jt.assistant.bean.Param
import com.jt.assistant.utils.GlideLoader
import com.jt.assistant.viewmodel.HomeViewModel
import com.orhanobut.logger.Logger
import com.yzp.mvvmlibrary.base.BaseActivity
import kotlinx.android.synthetic.main.activity_sku_pic_upload.*
import top.zibin.luban.Luban
import top.zibin.luban.OnCompressListener
import java.io.File

/**
 * 图片上传
 */
class SkuPicUploadActivity : BaseActivity<HomeViewModel>() {
    private val mAdapter by lazy {
        PicAdapter(
            ArrayList<String>()
        )
    }

    private var maxPicCount = 15//最大图片选择数量

    override fun layoutId(): Int = R.layout.activity_sku_pic_upload

    override fun initView(savedInstanceState: Bundle?) {
        with(rv_skuUpload) {
            layoutManager = GridLayoutManager(context, 3)
            canScrollVertically(0)
            adapter = mAdapter
            mAdapter.data.add("")
            mAdapter.notifyDataSetChanged()
        }
    }

    override fun initData() {
        ie_sku.mEdit.setText(intent.getStringExtra("SKU_NO").toString())
        maxPicCount -= intent.getIntExtra("SKU_PIC_NUM", 0)
        tv_skuTip.text = "上传图片(${maxPicCount}张)"
    }

    override fun initListener() {

        mAdapter.setOnItemClickListener { adapter, view, position ->
            if (mAdapter.data[position].isEmpty()) {
                ImagePicker.getInstance()
                    .setTitle("标题") //设置标题
                    .showCamera(true) //设置是否显示拍照按钮
                    .showImage(true) //设置是否展示图片
                    .showVideo(true) //设置是否展示视频
                    .showLoading(true, "请稍后...")
                    .setMaxCount(maxPicCount - mAdapter.itemCount + 1) //设置最大选择图片数目(默认为1，单选)
                    .setSingleType(true) //设置图片视频不能同时选择
                    .setImageLoader(GlideLoader()) //设置自定义图片加载器
                    .start(
                        this@SkuPicUploadActivity,
                        GlobalConfig.REQUEST_SELECT_IMAGES_CODE
                    ) //REQEST_SELECT_IMAGES_CODE为Intent调用的requestCode
            } else {//预览图
                startActivityForResult(
                    Intent(
                        this@SkuPicUploadActivity,
                        PreActivity::class.java
                    ).apply {
                        putExtra("IMAGEPATH", GsonUtils.toJson(mAdapter.data))
                        putExtra("POSITION", position)
                    }, GlobalConfig.PIC_REQUEST
                )
            }

        }

        bt_commit.setOnClickListener {
            val params = Param::class.java.newInstance()
            params.channelOrderNo = ""
            params.sku = intent.getStringExtra("SKU_NO").toString()
            viewModel.wareFile(params, mAdapter.data)
        }


        viewModel.mWareFile.observe(this, {
            if (it.isSuccess()) {
                speakString("上传成功")
                finish()
            }
        })
    }


    private fun imagePick(mImagePaths: ArrayList<String>?) {
        Luban.with(this)
            .load<String>(mImagePaths)
            .ignoreBy(100)
//            .setTargetDir(ImageUtil.getPath())
            .setFocusAlpha(false)
            .filter { path -> !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif")) }
            .setCompressListener(object : OnCompressListener {
                override fun onStart() {}

                @SuppressLint("SetTextI18n")
                override fun onSuccess(file: File) {
                    Logger.e(file.absolutePath)
                    mAdapter.data.add(0, file.absolutePath)
                    mAdapter.notifyDataSetChanged()
                    if ((mAdapter.data.size - 1) == maxPicCount) {
                        mAdapter.data.remove("")
                        mAdapter.notifyDataSetChanged()
                    }
                }

                override fun onError(e: Throwable) {
                    e.printStackTrace()
                }
            }).launch()
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == GlobalConfig.REQUEST_SELECT_IMAGES_CODE && resultCode == RESULT_OK) {
            imagePick(data!!.getStringArrayListExtra(ImagePicker.EXTRA_SELECT_IMAGES))
        }
        if (requestCode == GlobalConfig.PIC_REQUEST && resultCode == RESULT_OK) {
            val picList = GsonUtils.fromJson<ArrayList<String>>(
                data!!.getStringExtra(GlobalConfig.PIC_RESULT),
                object : TypeToken<ArrayList<String>>() {}.type
            )
            imagePickPre(picList)
        }
    }

    private fun imagePickPre(picList: ArrayList<String>?) {
        mAdapter.data.clear()
        if (picList!!.isNotEmpty()) {
            mAdapter.data.addAll(picList)
        }
        mAdapter.data.add("")
        if ((mAdapter.data.size - 1) == maxPicCount) {
            mAdapter.data.remove("")
        }
        mAdapter.notifyDataSetChanged()
    }


}